/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [UnsyncBank.java]
 * Creation Date        [02-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_08_thread.synchronization;

/**
 * 不同步的银行
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class UnsyncBank implements Bank {

	private final double[] accounts;

	public UnsyncBank(int n, double initialBalance) {
		accounts = new double[n];
		for (int i = 0; i < n; i++) {
			accounts[i] = initialBalance;
		}
	}

	@Override
	public void transfer(int fromAccount, int toAccount, double amount) {
		if (accounts[fromAccount] >= amount) {
			accounts[fromAccount] -= amount;
			System.out.printf(" %10.2f from %d to %d", amount, fromAccount,
					toAccount);
			accounts[toAccount] += amount;
			System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
		}
	}

	public double getTotalBalance() {
		double sum = 0;
		for (double d : accounts) {
			sum += d;
		}
		return sum;
	}

	@Override
	public int size() {
		return accounts.length;
	}

}
